package org.jeecg.modules.demo.com.kunpeng.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.modules.demo.com.kunpeng.entity.*;

import org.jeecg.modules.demo.com.kunpeng.entity.dto.ProjectCountQueryDTO;
import org.jeecg.modules.demo.com.kunpeng.mapper.*;

import org.jeecg.modules.demo.com.kunpeng.service.IProjectCountService;

import org.jeecg.modules.demo.com.kunpeng.service.ISaleContractCollectionPlanService;
import org.jeecg.modules.demo.com.kunpeng.service.ISaleContractDetailService;
import org.jeecg.modules.demo.com.kunpeng.service.ISaleContractService;
import org.jeecg.modules.demo.com.kunpeng.vo.SaleContractDetailVO;
import org.jeecg.modules.demo.com.kunpeng.vo.SaleContractVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
@Service
@Slf4j
public class ProjectCountServiceImpl extends ServiceImpl<ProjectCountMapper,ProjectCount> implements IProjectCountService {


    @Autowired
    private ProjectCountMapper projectCountMapper;

    @Autowired
    private ISaleContractService saleContractService;

    @Autowired
    private ProjectPurchaseMapper projectPurchaseMapper;

    @Autowired
    private ProjectPurchaseApplyMapper projectPurchaseApplyMapper;

    @Autowired
    private ISaleContractDetailService saleContractDetailService;

    @Autowired
    private ISaleContractCollectionPlanService saleContractCollectionPlanService;

    @Autowired
    private ProjectCostApplyMapper projectCostApplyMapper;

    @Autowired
    private ProjectDetailsMapper projectDetailsMapper;
    @Autowired
    private OaStepMapper oaStepMapper;

    /**
     * 项目统计列表
     * @return
     */
    @Override
    public Page<ProjectCount> projectCountList(Page<ProjectCount> page, ProjectCountQueryDTO projectCountQueryDTO) {
        List<ProjectCount> projectCounts = projectCountMapper.projectCountList(page, projectCountQueryDTO.getProjectNameOrId(), projectCountQueryDTO.getResponsibilityPerson(), projectCountQueryDTO.getKeyWords());
        if (projectCounts.size() > 0) {
            for (ProjectCount projectCount : projectCounts) {
                SaleContractDetailVO saleContractDetailVO = saleContractDetailService.selectProjectAmountByProjectId(projectCount.getProjectId());
                System.out.println("*************项目编号：" + projectCount.getProjectId());
                //如果销售合同详情不为空给销售金额赋值
                if (null != saleContractDetailVO) {
                    //项目统计表-销售金额
                    projectCount.setSaleAmount(saleContractDetailVO.getContractAmount());
                }
                //TODO  开票金额（待定）
                projectCount.setOpenInvoicingMoney(new BigDecimal(0));
                //TODO  回款金额（待定）
                projectCount.setReturnAmount(new BigDecimal(0));
                //TODO  剩余回款金额（待定）
                projectCount.setNoReturnAmount(new BigDecimal(0));
                //根据项目编号获取项目费用申请列表
                List<ProjectCostApply> projectCostApplies = projectCostApplyMapper.listByProjectId(projectCount.getProjectId());
                if (projectCostApplies.size() > 0) {
                    //其他支出
                    BigDecimal otherMoney = new BigDecimal(0.00);
                    //采购费用
                    BigDecimal purchaseMoney = new BigDecimal(0.00);
                    //未支付金额
                    BigDecimal surplusPayMoney = new BigDecimal(0.00);
                    //项目费用申请
                    for (ProjectCostApply projectCostApply : projectCostApplies) {
                        if (!projectCostApply.getCostType().equals("采购费用") && projectCostApply.getState().equals("3")) {
                            otherMoney = otherMoney.add(projectCostApply.getCostMoney());
                        } else if (projectCostApply.getCostType().equals("采购费用") && projectCostApply.getState().equals("3")) {
                            purchaseMoney = purchaseMoney.add(projectCostApply.getCostMoney());
                        } else if (projectCostApply.getState().equals("2")) {
                            surplusPayMoney = surplusPayMoney.add(projectCostApply.getCostMoney());
                        }
                    }
                    //项目统计其他支出赋值
                    projectCount.setOtherMoney(otherMoney);
                    //项目统计采购费用赋值
                    projectCount.setPurchaseMoney(purchaseMoney);
                    //已付金额=采购费用+其他支出
                    BigDecimal payMoney = otherMoney.add(purchaseMoney);
                    projectCount.setPayMoney(payMoney);
                    //剩余支付金额=所有已审核金额
                    projectCount.setSurplusPayMoney(surplusPayMoney);
                    //项目利润=销售金额-已付金额
                    if (null != saleContractDetailVO) {
                        projectCount.setProjectProfit(saleContractDetailVO.getContractAmount().subtract(payMoney));
                    }
                }
                //TODO 收票金额（待定）
                projectCount.setRecoveryInvoiceMoney(new BigDecimal(0));

                //获取项目阶段数据
                List<ProjectDetails> projectDetailsList = projectDetailsMapper.selectByMainId(projectCount.getId());
                if (projectDetailsList.size() > 0) {
                    //创建返回的项目阶段列表
                    List<ProjectCountDetailsStage> projectCountDetailsStageList = new ArrayList<>();
                    for (ProjectDetails projectDetails : projectDetailsList) {
                        System.out.println("项目阶段数据：" + projectDetails.toString());
                        //返回的项目阶段对象
                        ProjectCountDetailsStage projectCountDetailsStage = new ProjectCountDetailsStage();
                        //项目阶段值
                        projectCountDetailsStage.setProjectStage(projectDetails.getProjectPhase());
                        List<ProjectCostApply> projectCostAppliesList = projectCostApplyMapper.listByProjectId(projectCount.getProjectId());
                        if (projectCostAppliesList.size() > 0) {
                            log.info("项目统计详情获取到的项目费用申请列表：" + projectCostAppliesList.toString());
                            BigDecimal purchaseAmount = new BigDecimal(0.00);
                            BigDecimal otherAmount = new BigDecimal(0.00);
                            BigDecimal surplusPayMoney=new BigDecimal(0.00);
                            BigDecimal payMoney=new BigDecimal(0.00);
                            //遍历阶段内费用申请
                            for (ProjectCostApply projectCostApply:projectCostAppliesList){
                                if(projectCostApply.getProjectPhase().equals(projectDetails.getProjectPhase()) && projectCostApply.getCostType().equals("采购费用")
                                                                                    && projectCostApply.getState().equals("3")){
                                    purchaseAmount=purchaseAmount.add(projectCostApply.getCostMoney());
                                }
                                if(projectCostApply.getProjectPhase().equals(projectDetails.getProjectPhase()) && projectCostApply.getState().equals("3")){
                                    payMoney=payMoney.add(projectCostApply.getCostMoney());
                                }
                                if(projectCostApply.getProjectPhase().equals(projectDetails.getProjectPhase()) && projectCostApply.getState().equals("2")){
                                    surplusPayMoney=surplusPayMoney.add(projectCostApply.getCostMoney());
                                }
                                if(!projectCostApply.getCostType().equals("采购费用") && projectCostApply.getProjectPhase().equals(projectDetails.getProjectPhase())
                                                                                    && projectCostApply.getState().equals("3")){
                                    otherAmount=otherAmount.add(projectCostApply.getCostMoney());
                                }
                            }
                            //TODO 项目阶段收票金额(待定)
                            projectCountDetailsStage.setRecoveryInvoiceMoney(new BigDecimal(0));
                            //项目阶段采购金额
                            projectCountDetailsStage.setPurchaseMoney(purchaseAmount);
                            //项目阶段支付金额
                            projectCountDetailsStage.setPayMoney(payMoney);
                            //剩余付款金额
                            projectCountDetailsStage.setSurplusPayMoney(surplusPayMoney);
                            //项目阶段其他金额
                            projectCountDetailsStage.setOtherMoney(otherAmount);
                        }
                        //添加每个项目阶段到集合中
                        projectCountDetailsStageList.add(projectCountDetailsStage);
                    }
                    //给返回对象赋值项目阶段数据
                    projectCount.setProjectCountDetailsStage(projectCountDetailsStageList);
                }
            }
        }
        /*for (ProjectCount projectCount : projectCounts) {
            log.info("项目统计名称："+projectCount.getProjectName());
            SaleContractVO saleContractVO = saleContractService.selectByProjectName(projectCount.getProjectName());
            if(null!=saleContractVO){
                log.info("根据项目名称查询销售合同表数据："+saleContractVO.toString());
                SaleContractDetailVO saleContractDetailVO = saleContractDetailService.selectProjectAmountByProjectId(projectCount.getProjectId());
                //项目统计表-销售金额
                projectCount.setSaleAmount(saleContractDetailVO.getContractAmount());
                Double contractAmount = saleContractVO.getContractAmount().doubleValue();
                //项目统计表-开票金额
                //TODO  开票金额待定
                projectCount.setOpenInvoicingMoney(new BigDecimal(contractAmount*0.03));
                projectCount.setOpenInvoicingMoney(new BigDecimal(0));
                //获取销售合同收款计划列表
                List<SaleContractCollectionPlan> saleContractCollectionPlans = saleContractCollectionPlanService.selectByMainId(saleContractVO.getId());
                if(null!=saleContractCollectionPlans){
                    BigDecimal returnMoney=new BigDecimal(0.00);
                    //截止当前日期总的回款金额
                    for (SaleContractCollectionPlan saleContractCollectionPlan:saleContractCollectionPlans) {
                        Long nowTimeMillis = System.currentTimeMillis();
                        Calendar cal=Calendar.getInstance();
                        cal.setTime(saleContractCollectionPlan.getAgreedCollectionTime());
                        Long collectionMillis=cal.getTimeInMillis();
                        if(nowTimeMillis>collectionMillis){
                            BigDecimal amountCollected = saleContractCollectionPlan.getAmountCollected();
                            returnMoney=amountCollected.add(returnMoney);
                        }
                    }
                    //回款金额
                    projectCount.setReturnAmount(returnMoney);
                    projectCount.setReturnAmount(new BigDecimal(0));
                }
                //剩余回款金额
                projectCount.setNoReturnAmount(projectCount.getSaleAmount().subtract(projectCount.getReturnAmount()));
                projectCount.setNoReturnAmount(new BigDecimal(0));
                List<ProjectPurchase> projectPurchases = projectPurchaseMapper.listProjectPurchaseByPjId(projectCount.getProjectId());
                BigDecimal purchaseMoney=new BigDecimal(0.00);
                if(projectPurchases.size()>0){
                    for(ProjectPurchase projectPurchase:projectPurchases) {
                        log.info("项目采购表数据："+projectPurchase.toString());
                        purchaseMoney=purchaseMoney.add(projectPurchase.getPurchaseMoney());
                        //采购金额
                        projectCount.setPurchaseMoney(purchaseMoney);
                        //获取该项目采购数据关联采购申请
                        List<ProjectPurchaseApply> projectPurchaseApplies = projectPurchaseApplyMapper.listByPPId(projectPurchase.getId());
                        if (projectPurchaseApplies.size() > 0) {
                            BigDecimal recoveryInvoiceMoney = new BigDecimal(0.00);
                            BigDecimal payMoney = new BigDecimal(0.00);
                            for (ProjectPurchaseApply projectPurchaseApply : projectPurchaseApplies) {
                                double unitPrice = projectPurchaseApply.getUnitPrice().doubleValue();
                                //TODO 收票金额待定
                                recoveryInvoiceMoney=recoveryInvoiceMoney.add(new BigDecimal(unitPrice * projectPurchaseApply.getRequestedQuantity() * 0.03));
                                payMoney=payMoney.add(new BigDecimal(unitPrice * projectPurchaseApply.getRequestedQuantity()));
                            }
                            //收票金额
                            projectCount.setRecoveryInvoiceMoney(recoveryInvoiceMoney);
                            //已付金额
                            projectCount.setPayMoney(payMoney);
                        }
                    }
                }
                //其他支出
                BigDecimal otherMoney=new BigDecimal(0.00);
                //采购费用
                BigDecimal purchaseMoney=new BigDecimal(0.00);
                List<ProjectCostApply> projectCostApplies = projectCostApplyMapper.listByProjectId(projectCount.getProjectId());
                if(projectCostApplies.size()>0){
                    //项目费用申请
                    for(ProjectCostApply projectCostApply:projectCostApplies){
                        if(!projectCostApply.getCostType().equals("采购费用")){
                            otherMoney=otherMoney.add(projectCostApply.getCostMoney());
                        }else {
                            purchaseMoney=purchaseMoney.add(projectCostApply.getCostMoney());
                        }
                    }
                    //项目统计其他支出赋值
                    projectCount.setOtherMoney(otherMoney);
                    //项目统计采购费用赋值
                    projectCount.setPurchaseMoney(purchaseMoney);
                    //TODO 收票金额待定
                    projectCount.setRecoveryInvoiceMoney((otherMoney.add(purchaseMoney)).multiply(new BigDecimal(0.03)));
                    projectCount.setRecoveryInvoiceMoney(new BigDecimal(0));
                    //已付金额
                    projectCount.setPayMoney(otherMoney.add(purchaseMoney));
                }
                if(null!=saleContractVO && null!=purchaseMoney){
                    //项目利润：销售金额-采购金额-其他支出
                    projectCount.setProjectProfit(saleContractVO.getContractAmount().subtract(purchaseMoney).subtract(otherMoney));
                }else if(null!=saleContractVO){
                    //项目利润：销售金额-其他支出
                    projectCount.setProjectProfit(saleContractVO.getContractAmount().subtract(otherMoney));
                }
            }

            System.out.println("项目统计数据："+projectCount.toString());
            //获取项目阶段数据
            List<ProjectDetails> projectDetailsList = projectDetailsMapper.selectByMainId(projectCount.getId());
            if(projectDetailsList.size()>0){
                //创建返回的项目阶段列表
                List<ProjectCountDetailsStage> projectCountDetailsStageList=new ArrayList<>();
                for(ProjectDetails projectDetails:projectDetailsList){
                    System.out.println("项目阶段数据："+projectDetails.toString());
                    //返回的项目阶段对象
                    ProjectCountDetailsStage projectCountDetailsStage=new ProjectCountDetailsStage();
                    //项目阶段值
                    projectCountDetailsStage.setProjectStage(projectDetails.getProjectPhase());
                    //获取项目阶段采购金额
                    //获取项目阶段开始和结束时间
                    Date projectStartTime = projectDetails.getStartTime();
                    Date projectEndTime = projectDetails.getEndTime();
                    List<ProjectCostApply> projectCostApplies = projectCostApplyMapper.listByProjectId(projectCount.getProjectId());
                    if(projectCostApplies.size()>0){
                        log.info("项目统计详情获取到的项目费用申请列表："+projectCostApplies.toString());
                        BigDecimal purchaseAmount=new BigDecimal(0.00);
                        BigDecimal otherAmount=new BigDecimal(0.00);
                        for(ProjectCostApply projectCostApply:projectCostApplies){
                            //费用预期使用时间
                            Date expectTime = projectCostApply.getExpectTime();
                            Calendar cal=Calendar.getInstance();
                            cal.setTime(projectStartTime);
                            //项目阶段开始时间时间戳
                            Long projectStartMillis=cal.getTimeInMillis();
                            cal.setTime(projectEndTime);
                            //项目阶段结束时间时间戳
                            Long projectEndMillis=cal.getTimeInMillis();
                            cal.setTime(expectTime);
                            //费用申请时间时间戳
                            Long expectTimeMillis=cal.getTimeInMillis();
                            if(expectTimeMillis>projectStartMillis && expectTimeMillis<projectEndMillis && projectCostApply.getCostType().equals("采购费用")){
                                purchaseAmount=purchaseAmount.add(projectCostApply.getCostMoney());
                            }
                            log.info("purchaseAmount:"+purchaseAmount);
                            if(expectTimeMillis>projectStartMillis && expectTimeMillis<projectEndMillis && !projectCostApply.getCostType().equals("采购费用")){
                                otherAmount=otherAmount.add(projectCostApply.getCostMoney());
                            }
                        }
                        //TODO 项目阶段收票金额
                        projectCountDetailsStage.setRecoveryInvoiceMoney((purchaseAmount.add(otherAmount)).multiply(new BigDecimal(0.03)));
                        //项目阶段采购金额
                        projectCountDetailsStage.setPurchaseMoney(purchaseAmount);
                        //项目阶段支付金额
                        projectCountDetailsStage.setPayMoney(purchaseAmount);
                        projectCountDetailsStage.setSurplusPayMoney(new BigDecimal(0.00));
                        //项目阶段其他金额
                        projectCountDetailsStage.setOtherMoney(otherAmount);
                    }
                    //添加每个项目阶段到集合中
                    projectCountDetailsStageList.add(projectCountDetailsStage);
                }
                //给返回对象赋值项目阶段数据
                projectCount.setProjectCountDetailsStage(projectCountDetailsStageList);
            }
        }
        }*/
            page.setRecords(projectCounts);
            return page;
        }


    /**
     * oa项目统计
     * @param page
     * @param projectCountQueryDTO
     * @return
     */
    @Override
    public Page<OaProjectCount> OaProjectCountList(Page<OaProjectCount> page, ProjectCountQueryDTO projectCountQueryDTO) {
        //获取项目列表
        List<OaProjectCount> oaProjectCounts = projectCountMapper.OaProjectCountList(page,projectCountQueryDTO.getProjectNameOrId(), projectCountQueryDTO.getKeyWords());
        //如果项目列表不为空，遍历赋值

        if(oaProjectCounts.size()>0){
            for (OaProjectCount oaProjectCount:oaProjectCounts) {
                /*System.out.println("***************************"+oaProjectCount.toString());*/
                //TODO  项目统计表-销售金额已赋值（待验证）
                /*oaProjectCount.setSaleAmount(new BigDecimal(0));*/
                /*System.out.println("OA项目id:"+oaProjectCount.getProjectId());*/
                SaleContractDetailVO saleContractDetailVO = saleContractDetailService.selectProjectAmountByProjectId(oaProjectCount.getProjectId());
                if(null!=saleContractDetailVO){
                    oaProjectCount.setSaleAmount(saleContractDetailVO.getContractAmount());
                }
                //TODO  开票金额（待定）
                oaProjectCount.setOpenInvoicingMoney(new BigDecimal(0));
                //TODO  剩余回款金额已赋值
                /*System.out.println("**回款金额："+oaProjectCount.getReturnAmount());
                System.out.println("**已回款金额："+oaProjectCount.getAlreadyReturnMoney());*/
                oaProjectCount.setNoReturnAmount(oaProjectCount.getReturnAmount().subtract(oaProjectCount.getAlreadyReturnMoney()));
                //TODO  回款金额已赋值
                oaProjectCount.setReturnAmount(oaProjectCount.getAlreadyReturnMoney());

                //根据项目编号获取项目费用申请列表
                List<ProjectCostApply> projectCostApplies = projectCostApplyMapper.listByProjectId(oaProjectCount.getProjectId());
                if (projectCostApplies.size() > 0) {
                    //其他支出
                    BigDecimal otherMoney = new BigDecimal(0.00);
                    //采购费用
                    BigDecimal purchaseMoney = new BigDecimal(0.00);
                    //未支付金额
                    BigDecimal surplusPayMoney = new BigDecimal(0.00);
                    //项目费用申请
                    for (ProjectCostApply projectCostApply : projectCostApplies) {
                        if (!projectCostApply.getCostType().equals("3") && projectCostApply.getState().equals("2")) {
                            otherMoney = otherMoney.add(projectCostApply.getCostMoney());
                        } else if (projectCostApply.getCostType().equals("3") && projectCostApply.getState().equals("2")) {
                            purchaseMoney = purchaseMoney.add(projectCostApply.getCostMoney());
                        } else if (projectCostApply.getState().equals("1")) {
                            surplusPayMoney = surplusPayMoney.add(projectCostApply.getCostMoney());
                        }
                    }
                    //项目统计其他支出赋值
                    oaProjectCount.setOtherMoney(otherMoney);
                    //项目统计采购费用赋值
                    oaProjectCount.setPurchaseMoney(purchaseMoney);
                    //已付金额=采购费用+其他支出
                    BigDecimal payMoney = otherMoney.add(purchaseMoney);
                    oaProjectCount.setPayMoney(payMoney);
                    //剩余支付金额=所有已审核金额
                    oaProjectCount.setSurplusPayMoney(surplusPayMoney);
                    //TODO 项目利润=销售金额-已付金额(合同模块处理好后修改-待验证)
                    /*oaProjectCount.setProjectProfit(new BigDecimal(0));*/
                    if (null != saleContractDetailVO) {
                        oaProjectCount.setProjectProfit(saleContractDetailVO.getContractAmount().subtract(payMoney));
                    }
                }
                //TODO 收票金额（待定）
                oaProjectCount.setRecoveryInvoiceMoney(new BigDecimal(0));

                //根据项目id获取项目阶段数据
                List<OaStep> oaSteps = oaStepMapper.listOaStep(oaProjectCount.getId());

                if (oaSteps.size() > 0) {
                    //创建返回的项目阶段列表
                    List<ProjectCountDetailsStage> projectCountDetailsStageList = new ArrayList<>();
                    for (OaStep oaStep : oaSteps) {
                        /*System.out.println("项目阶段数据：" + oaStep.toString());*/
                        //返回的项目阶段对象
                        ProjectCountDetailsStage projectCountDetailsStage = new ProjectCountDetailsStage();
                        //项目阶段值
                        projectCountDetailsStage.setProjectStage(oaStep.getFlowName());
                        //根据项目编号获取项目费用申请列表
                        List<ProjectCostApply> projectCostAppliesList = projectCostApplyMapper.listByProjectId(oaProjectCount.getProjectId());

                        if (projectCostAppliesList.size() > 0) {
                            /*log.info("项目统计详情获取到的项目费用申请列表：" + projectCostAppliesList.toString());*/
                            BigDecimal purchaseAmount = new BigDecimal(0.00);
                            BigDecimal otherAmount = new BigDecimal(0.00);
                            BigDecimal surplusPayMoney=new BigDecimal(0.00);
                            BigDecimal payMoney=new BigDecimal(0.00);
                            //遍历阶段内费用申请
                            for (ProjectCostApply projectCostApply:projectCostAppliesList){
                                if(projectCostApply.getProjectPhase().equals(oaStep.getFlowName()) && projectCostApply.getCostType().equals("3") && projectCostApply.getState().equals("2")){
                                    purchaseAmount=purchaseAmount.add(projectCostApply.getCostMoney());
                                }
                                if(projectCostApply.getProjectPhase().equals(oaStep.getFlowName()) && projectCostApply.getState().equals("2")){
                                    payMoney=payMoney.add(projectCostApply.getCostMoney());
                                }
                                if(projectCostApply.getProjectPhase().equals(oaStep.getFlowName()) && projectCostApply.getState().equals("1")){
                                    surplusPayMoney=surplusPayMoney.add(projectCostApply.getCostMoney());
                                }
                                if(!projectCostApply.getCostType().equals("3") && projectCostApply.getProjectPhase().equals(oaStep.getFlowName())
                                        && projectCostApply.getState().equals("2")){
                                    otherAmount=otherAmount.add(projectCostApply.getCostMoney());
                                }
                            }
                            //TODO 项目阶段收票金额(待定)
                            projectCountDetailsStage.setRecoveryInvoiceMoney(new BigDecimal(0));
                            //项目阶段采购金额
                            projectCountDetailsStage.setPurchaseMoney(purchaseAmount);
                            //项目阶段支付金额
                            projectCountDetailsStage.setPayMoney(payMoney);
                            //剩余付款金额
                            projectCountDetailsStage.setSurplusPayMoney(surplusPayMoney);
                            //项目阶段其他金额
                            projectCountDetailsStage.setOtherMoney(otherAmount);
                        }
                        //添加每个项目阶段到集合中
                        projectCountDetailsStageList.add(projectCountDetailsStage);
                    }
                    //给返回对象赋值项目阶段数据
                    oaProjectCount.setProjectCountDetailsStage(projectCountDetailsStageList);
                }
            }
        }
        //把项目统计数据赋值到分页信息中返回
        page.setRecords(oaProjectCounts);
        return page;
    }
}
